package network;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;


//客户端
public class TcpEchoClient {

    private Socket socket = null;

    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //与服务器建立连接,相当于两端通话中先拨打电话的一方
        socket = new Socket(serverIp,serverPort);
    }

    public void start() {
        System.out.println("客户端(崩铁)启动!!!");
        //首先从键盘上读取客户说输入的数据
        Scanner scannerRequest = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while (true) {
                String request = scannerRequest.next();
                if (request.equals("exit")) {
                    System.out.println("断开与服务器的连接!");
                    break;
                }
                //构造流对象用来发送请求和接受响应
                //发送请求
                //注意outputStream不能发送字符串,所以这里借助 PrintWriter 来发送
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //刷新一下缓冲区,确保数据已经发送出去了
                printWriter.flush();
                //接下来接受响应
                Scanner scannerResponse = new Scanner(inputStream);
                String response = scannerResponse.next();
                //打印返回的响应数据
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
